// 初始化 ECharts 实例
var pieDom = document.getElementById('pie');
var pieChart = echarts.init(pieDom);
var lineDom = document.getElementById('line');
var lineChart = echarts.init(lineDom);

// 初始化图表配置
var pieOption = {
    tooltip: {
        trigger: 'item'
    },
    legend: {
        top: '5%',
        left: 'center'
    },
    color: ['#3ba272', '#ee4455',  '#91cc75' ,'#ee6666'],
    series: [
        {
            name: '场数占比',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            padAngle: 5,
            itemStyle: {
                borderRadius: 10
            },
            emphasis: {
                label: {
                  show: true,
                  fontSize: 40,
                  fontWeight: 'bold'
                }
            },
            label: {
                show: true,
                position: 'outside'
            },
            labelLine: {
                show: true
            },
            data: [
                { value: 0, name: '地主胜场' },
                { value: 0, name: '地主败场' },
                { value: 0, name: '农民胜场' },
                { value: 0, name: '农民败场' }
            ]
        }
    ]
};

var lineOption = {
    tooltip: {
        trigger: 'axis'
    },
    legend: {
        data: ['地主胜率', '农民胜率', '总胜率']
    },
    xAxis: {
        type: 'category',
        data: [] // 横坐标为空数组，动态填充
    },
    yAxis: {
        type: 'value',
        axisLabel: {
            formatter: '{value}%'
        }
    },
    series: [
        {
            name: '地主胜率',
            type: 'line',
            data: [] // 数据为空，动态填充
        },
        {
            name: '农民胜率',
            type: 'line',
            data: [] // 数据为空，动态填充
        },
        {
            name: '总胜率',
            type: 'line',
            data: [] // 数据为空，动态填充
        }
    ]
};

// 设置初始图表
pieChart.setOption(pieOption);
lineChart.setOption(lineOption);


// 初始化计数
let landlordWinCount = 0;
let landlordLossCount = 0;
let farmerWinCount = 0;
let farmerLossCount = 0;
// 初始化历史栈，最多保存5次状态
let historyStack = [];

// 初始化胜率记录数组，初始时设置为 [0]，表示初始胜率为 0%
let landlordWinRateHistory = [0];
let farmerWinRateHistory = [0];
let totalWinRateHistory = [0];

// 监听键盘事件
document.addEventListener('keydown', handleKeyEvent);

// 处理键盘事件
function handleKeyEvent(event) {
    switch (event.key) {
        case 'z': case 'x': case 'c': case 'v':
            handleIncrement(event.key); // 处理增加
            break;
        case 'a': case 's': case 'd': case 'f':
            handleDecrement(event.key); // 处理减少
            break;
        default:
            break;
    }
}

// 处理增加操作
function handleIncrement(key) {
    const operations = {
        'z': ['landlord', 'win'],
        'x': ['landlord', 'loss'],
        'c': ['farmer', 'win'],
        'v': ['farmer', 'loss']
    };
    const [type, result] = operations[key];
    updateCount(type, result, 1); // 增加操作
}

// 处理减少操作
function handleDecrement(key) {
    undo();
}

// 更新计数并计算胜率
function updateCount(type, result, change = 1) {
    // 先保存当前状态到历史栈（最大保存5次）
    if (historyStack.length >= 5) {
        historyStack.shift(); // 超过5次，删除最旧的历史
    }
    historyStack.push({
        landlordWinCount,
        landlordLossCount,
        farmerWinCount,
        farmerLossCount
    });

    // 进行计数更新
    if (type === 'landlord') {
        if (result === 'win') {
            landlordWinCount += change;
        } else if (result === 'loss') {
            landlordLossCount += change;
        }
    } else if (type === 'farmer') {
        if (result === 'win') {
            farmerWinCount += change;
        } else if (result === 'loss') {
            farmerLossCount += change;
        }
    }

    // 计算胜率，避免出现0/0导致NaN，取整
    const landlordWinRate = (landlordWinCount + landlordLossCount) > 0 ? Math.round(landlordWinCount / (landlordWinCount + landlordLossCount) * 100) : 0;
    const farmerWinRate = (farmerWinCount + farmerLossCount) > 0 ? Math.round(farmerWinCount / (farmerWinCount + farmerLossCount) * 100) : 0;
    const totalWinRate = (landlordWinCount + landlordLossCount + farmerWinCount + farmerLossCount) > 0 ? Math.round((landlordWinCount + farmerWinCount) / (landlordWinCount + landlordLossCount + farmerWinCount + farmerLossCount) * 100) : 0;

    // 更新历史胜率数组
    landlordWinRateHistory.push(landlordWinRate);
    farmerWinRateHistory.push(farmerWinRate);
    totalWinRateHistory.push(totalWinRate);

    // 更新页面显示
    updateDisplay();
    // 更新时间
    updateEndTime();

}

// 撤销操作
function undo() {
    if (historyStack.length === 0) return; // 如果没有历史记录，则不执行撤销

    // 恢复到上一次的状态
    const lastState = historyStack.pop();
    landlordWinCount = lastState.landlordWinCount;
    landlordLossCount = lastState.landlordLossCount;
    farmerWinCount = lastState.farmerWinCount;
    farmerLossCount = lastState.farmerLossCount;

    // 撤销胜率记录
    landlordWinRateHistory.pop();
    farmerWinRateHistory.pop();
    totalWinRateHistory.pop();

    // 更新页面显示
    updateDisplay();
}

// 更新页面显示
function updateDisplay() {
    // 从当前的计数值和历史数组中获取最新数据
    const totalGames = landlordWinCount + landlordLossCount + farmerWinCount + farmerLossCount;

    const landlordWinRate = landlordWinRateHistory[landlordWinRateHistory.length - 1];
    const farmerWinRate = farmerWinRateHistory[farmerWinRateHistory.length - 1];
    const totalWinRate = totalWinRateHistory[totalWinRateHistory.length - 1];


    // 更新显示的 DOM 元素
    document.getElementById('landlordWinCount').textContent = landlordWinCount;
    document.getElementById('landlordLossCount').textContent = landlordLossCount;
    document.getElementById('farmerWinCount').textContent = farmerWinCount;
    document.getElementById('farmerLossCount').textContent = farmerLossCount;
    document.getElementById('landlordWinRate').textContent = landlordWinRate + '%';
    document.getElementById('farmerWinRate').textContent = farmerWinRate + '%';
    document.getElementById('totalWinRate').textContent = totalWinRate + '%';
    document.getElementById('totalGames').textContent = totalGames;

    // 更新 ECharts 饼图
    updatePieChart();
    // 更新 ECharts 折线图
    updateLineChart();

    // 颜色更新函数
    updateWinRateColors(landlordWinRate, farmerWinRate, totalWinRate);
    // 豆子面板更新
    updateAdditionalStats();
}


// 更新 ECharts 饼图
function updatePieChart() {
    // 更新图表数据
    pieChart.setOption({
        series: [{
            data: [
                { value: landlordWinCount, name: '地主胜场' },
                { value: landlordLossCount, name: '地主败场' },
                { value: farmerWinCount, name: '农民胜场' },
                { value: farmerLossCount, name: '农民败场' }
            ]
        }]
    });
}
// 更新 ECharts 折线图
function updateLineChart() {
    lineChart.setOption({
        xAxis: {
            data: Array.from({ length: landlordWinRateHistory.length }, (_, i) => i + 1) // 动态填充横坐标
        },
        series: [
            { data: landlordWinRateHistory },
            { data: farmerWinRateHistory },
            { data: totalWinRateHistory }
        ]
    });
}


    // 根据胜率更新背景色
function updateWinRateColors(landlordWinRate, farmerWinRate, totalWinRate) {
    // 胜率背景色设置
    const landlordRateCell = document.getElementById('landlordWinRate');
    const farmerRateCell = document.getElementById('farmerWinRate');
    const totalRateCell = document.getElementById('totalWinRate');

    // 更新地主胜率背景色
    landlordRateCell.style.backgroundColor = getBackgroundColor(landlordWinRate);

    // 更新农民胜率背景色
    farmerRateCell.style.backgroundColor = getBackgroundColor(farmerWinRate);

    // 更新总胜率背景色
    totalRateCell.style.backgroundColor = getBackgroundColor(totalWinRate);
}

// 根据胜率值返回背景色
function getBackgroundColor(winRate) {
    if (winRate <= 50) {
        return '#FFCCCC'; // 浅红色
    } else if (winRate <= 60) {
        return '#CCCCFF'; // 浅蓝色
    } else if (winRate <= 70) {
        return '#CCFFCC'; // 浅绿色
    } else {
        return 'gold'; // 金色
    }
}
// 更新净胜场、消耗豆子数和总分数
function updateAdditionalStats() {
    // 计算净胜场
    const netWinCount = (landlordWinCount + farmerWinCount) - (landlordLossCount + farmerLossCount);

    // 计算消耗豆子数
    const beanConsumption = (landlordLossCount * 1800) + (farmerLossCount * 900);

    // 计算总分数
    const totalScore = ((landlordWinCount - landlordLossCount) * 1800) + ((farmerWinCount - farmerLossCount) * 900);

    // 更新表格中的字段值
    document.getElementById('netWinCount').textContent = netWinCount;
    document.getElementById('beanConsumption').textContent = beanConsumption;
    document.getElementById('totalScore').textContent = totalScore;
}
// 格式化时间函数
function formatTime(date) {
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
}

// 初始化函数：将 startTime 和 endTime 设置为当前时间
function initializeTime() {
    const currentTime = new Date();
    // 设置开始时间为当前时间
    document.getElementById('startTime').textContent = formatTime(currentTime);
    // 设置结束时间为当前时间
    document.getElementById('endTime').textContent = formatTime(currentTime);
}

// 更新时间函数：仅更新 endTime
function updateEndTime() {
    const currentTime = new Date();
    // 设置结束时间为当前时间
    document.getElementById('endTime').textContent = formatTime(currentTime);
}

// 页面加载完成后调用初始化函数
window.onload = function() {
    initializeTime();
};
